#include "maininterface.h"

Maininterface::Maininterface(QWidget* parent):
    parent(parent)
{
    Init();

    // 创建中心部件和水平布局
    centralWidget = new QWidget(this);
    layout = new QHBoxLayout(centralWidget);
    this->resize(1200,800);

    // 创建并添加菜单栏
    menuBar = new QMenuBar(this);

    fileAction = new QAction("消息", this);
    connect(fileAction, &QAction::triggered, this, &Maininterface::onFileMenuTriggered);
    menuBar->addAction(fileAction);

    personAction = new QAction("联系人", this);
    connect(personAction, &QAction::triggered, this, &Maininterface::onPersonMenuTriggered);
    menuBar->addAction(personAction);


    setMenuBar(menuBar);

    // 创建消息列表
    messageList = new QListWidget(this);
    messageList->setFixedWidth(350); // 设置列表宽度
    layout->addWidget(messageList);
    messageList->addItem("Stm32交流群\n龙星：你好");
    messageList->addItem("交流群\n龙星：666");

    // 连接 itemClicked 信号到自定义的槽函数
    connect(messageList, &QListWidget::itemClicked, this, &Maininterface::onListItemClicked);

    layout1 = new QVBoxLayout(this);
    // 聊天消息窗口
    listWidget = new QListWidget(this);
    listWidget->setStyleSheet("QListWidget { background-color: rgba(255, 255, 255, 55); }");
//    listWidget->addItem("Stm32交流群龙星：你好");
//    listWidget->addItem("交流群龙星：666");
    layout1->addWidget(listWidget);

    // 创建水平布局
    buttonLayout = new QHBoxLayout();
    buttonList = new QList<QPushButton* >();

    // 创建四个按钮并添加到水平布局中
    QPushButton *button1 = new QPushButton("截图", this);
    buttonList->append(button1);
    buttonLayout->addWidget(button1);
    connect(button1,&QPushButton::clicked,this,&Maininterface::onButton1Clicked);
    QPushButton *button2 = new QPushButton("录屏", this);
    buttonList->append(button2);
    buttonLayout->addWidget(button2);
    connect(button1,&QPushButton::clicked,this,&Maininterface::onButton2Clicked);
    QPushButton *button3 = new QPushButton("图片", this);
    buttonList->append(button3);
    buttonLayout->addWidget(button3);
    QPushButton *button4 = new QPushButton("文件", this);
    buttonList->append(button4);
    buttonLayout->addWidget(button4);


    // 将水平布局添加到垂直布局中
    layout1->addLayout(buttonLayout);

    // 设置编辑框
    textEdit = new QTextEdit(this);
    layout1->addWidget(textEdit);
    sendButton = new QPushButton("发送");

    // 设置按钮的最小尺寸（你可以根据需要调整这些值）
    sendButton->setMinimumSize(100, 50);
    connect(sendButton,&QPushButton::clicked,this,&Maininterface::sendButtonClicked);
//    layout1->addWidget(sendButton,0);

    // 创建一个水平布局
    layout2 = new QHBoxLayout();
    // 创建一个弹簧并设置宽度占比
    spacer = new QSpacerItem(300, 20, QSizePolicy::Expanding, QSizePolicy::Fixed);
    // 将弹簧添加到布局中
    layout2->addItem(spacer);
    layout2->addWidget(sendButton,0);

    layout1->addLayout(layout2);
    layout->addLayout(layout1,1);

    // 设置中心部件
    setCentralWidget(centralWidget);

    timer = new QTimer();
    connect(timer, &QTimer::timeout,this, &Maininterface::HttpPost);
//    timer->start(2000); // 设置定时器每隔1000毫秒（1秒）触发一次

    //废弃方案
//    HttpPost();
//    std::thread t(ThreadRecv,this);
//    t.detach();
}


//void ThreadRecv(Maininterface* maininterface)
//{
//    // 群聊还是好友|发送者|接受者|信息
//    QString realText= QString("1")+":"+"1"+":"+"2"+":";
//    while(true){
////        qDebug()<<"ok"<<Qt::endl;
//        if(maininterface->RecvMessage){
//            qDebug()<<"true"<<Qt::endl;
//            maininterface->Httprecv(realText);
//            // 线程睡眠1秒

//        }
//        QThread::sleep(1); // 这里的参数是毫秒，所以1000毫秒等于1秒
//    }
//    //    return 0;
//}

void Maininterface::sendButtonClicked(){
//    qDebug()<<listWidget->size()<<Qt::endl;
    QSize listWidgetSize = listWidget->size();
    QString sendText = textEdit->toPlainText();

    textEdit->clear();

    if(sendText == ""){
        return;
    }
    qDebug()<<"send:"<<sendText<<Qt::endl;
    // 创建一个 QListWidgetItem
//    QListWidgetItem *item = new QListWidgetItem(sendText);

//    // 设置文本对齐方式为右对齐
//    item->setTextAlignment(Qt::AlignRight);
//    // 将 QListWidgetItem 添加到 QListWidget
//    listWidget->addItem(item);

    // 创建一个QWidget作为列表项
    QWidget *itemWidget = new QWidget();
    QWidget *itWidget = new QWidget();
//    QLayout *layout = new QLayout(itemWidget);
    QVBoxLayout* label = new QVBoxLayout(itWidget);
    QHBoxLayout *layout = new QHBoxLayout(itemWidget);

    QLabel *nameLabel = new QLabel("龙星");
    // 创建并设置文本标签
    QLabel *textLabel = new QLabel(sendText);
    // 设置样式表，使QLabel具有白色背景和黑色文本
    textLabel->setStyleSheet("QLabel {"
                             "    background-color: white;" // 设置背景颜色为白色
                             "    color: black;" // 设置文本颜色为黑色
                             "    border: 1px white;" // 设置边框为灰色，宽度为1像素
                             "    padding: 5px;" // 设置内边距为5像素
                             "    margin: 5px;" // 设置外边距为5像素
                             "    border-radius: 5px;" // 设置边框圆角为5像素
                             "}");
    QSize textLabelSize = textLabel->sizeHint();
//    layout->addStretch(); // 添加弹性空间以将图像推到右侧
//    layout->addWidget(textLabel);
    qDebug()<<textLabel->sizeHint()<<Qt::endl;
    // 创建并设置头像标签（这里假设您有一个头像的QPixmap）
    QLabel *imageLabel = new QLabel();
    QPixmap pixmap("D:/QtCode/QQ/QQ/1.jpg"); // 替换为您的头像路径
    imageLabel->setPixmap(pixmap.scaled(60, 60, Qt::KeepAspectRatio)); // 调整头像大小
    imageLabel->setContentsMargins(0, 20, 0, 0);
    int width = listWidgetSize.width()/2;
    int count = textLabelSize.width()/width;
    if(count > 0){
        int fixedDistance = sendText.length()/count; // 设置固定距离为3

        for (int i = fixedDistance; i < sendText.length(); i += fixedDistance + 1) {
            sendText = sendText.insert(i, '\n');
        }
//        qDebug()<<sendText<<Qt::endl;

    }
    textLabel->setText(sendText);
    layout->addStretch(); // 添加弹性空间以将图像推到右侧
    label->addWidget(nameLabel,0,Qt::AlignRight);
    label->addWidget(textLabel);
    layout->addWidget(itWidget);
//    layout->addWidget(nameLabel);
//    layout->addWidget(textLabel);
    layout->addWidget(imageLabel,0,Qt::AlignTop);

    QListWidgetItem *listItem = new QListWidgetItem(listWidget);
    listItem->setSizeHint(itemWidget->sizeHint());
    listWidget->addItem(listItem);
    listWidget->setItemWidget(listItem, itemWidget);
    listWidget->scrollToBottom();

    // 群聊还是好友|发送者|接受者|信息
    QString realText= QString("1")+":"+"1"+":"+"2"+":"+sendText;

    Httprequest(realText);
//    Httprecv(realText);
}



void Maininterface::Init(){
//    shadewidget = new Shadewidget(this);
}

void Maininterface::onFileMenuTriggered()
{
    messageList->clear();
    this->textEdit->clear();
    textEdit->clear();
}

void Maininterface::onPersonMenuTriggered()
{
    messageList->clear();
    this->textEdit->clear();
    textEdit->clear();
}

void Maininterface::onListItemClicked(QListWidgetItem *item){
    qDebug() << "点击了消息：" << item->text();
}

// 截图
void Maininterface::onButton1Clicked(){
    if(shadewidget != nullptr){
        delete shadewidget;
        shadewidget = nullptr;
    }
    shadewidget = new Shadewidget(this);
    this->hide();
    shadewidget->show();
}

void Maininterface::onButton2Clicked(){

}

void Maininterface::onButton3Clicked(){

}

void Maininterface::onButton4Clicked(){

}


// 假设这是你的槽函数，用于处理请求完成后的数据
void Maininterface::handleRequestNetworkData() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (reply->error()) {
        qDebug() << "Request failed:" << reply->errorString();
        return;
    }

    QString response = reply->readAll();
    qDebug() << "Response:" << response;

    reply->deleteLater(); // 清理reply对象
}



// 发送消息
void Maininterface::Httprequest(QString text)
{
    // 创建 QNetworkAccessManager 实例
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    // 设置请求的 URL
    QUrl url("http://8.137.19.230:8080/QtWrite"); // 替换为你要请求的URL

    // 创建 QHttpMultiPart 实例用于存储 form-data
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    // 添加表单字段
    QHttpPart part;
    part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=text"));
    part.setBody(text.toUtf8()); // 设置字段的值
    multiPart->append(part);

    // 创建请求
    QNetworkRequest request(url);

//    // 设置请求的 Content-Type 为 multipart/form-data
//    request.setHeader(QNetworkRequest::ContentTypeHeader, multiPart->contentType());
//    request.setRawHeader("Content-Type", multiPart->contentType().toUtf8());
    // 发送 POST 请求
    QNetworkReply *reply = manager->post(request, multiPart);
    connect(reply, &QNetworkReply::finished, this, &Maininterface::handleRequestNetworkData);
//    QString response = reply->readAll();
//    qDebug()<<"response:"<<response<<Qt::endl;
}

// 假设这是你的槽函数，用于处理请求完成后的数据
void Maininterface::handleRecvNetworkData() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (reply->error()) {
        qDebug() << "Request failed:" << reply->errorString();
        return;
    }

    QString response = reply->readAll();
    qDebug() << "Response:" << response;

    listWidget->addItem(response);

    reply->deleteLater(); // 清理reply对象
}

// 接收消息
void Maininterface::Httprecv(QString text)
{
    // 创建 QNetworkAccessManager 实例
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    // 设置请求的 URL
    QUrl url("http://8.137.19.230:8080/QtRead"); // 替换为你要请求的URL

    // 创建 QHttpMultiPart 实例用于存储 form-data
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    // 添加表单字段
    QHttpPart part;
    part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=text"));
    part.setBody(text.toUtf8()); // 设置字段的值
    multiPart->append(part);

    // 创建请求
    QNetworkRequest request(url);

    // 发送 POST 请求
    QNetworkReply* reply = manager->post(request, multiPart);

//    QEventLoop loop;
//    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
//    loop.exec(); // 阻塞直到 finished() 信号发出

//    QString response = reply->readAll();
//    qDebug() << "Response:" << response;

//    listWidget->addItem(response);

//    reply->deleteLater(); // 清理reply对象


    connect(reply, &QNetworkReply::finished, this, &Maininterface::handleRecvNetworkData);

}

void Maininterface::HttpPost(){
    if(RecvMessage){
        Httprecv("1:1:1:1");
    }
}
